// 创建用户相关的小仓库
import { defineStore } from 'pinia'
// 引入请求登陆
import { reqLogin, reqUserInfo } from '@/api/user/index'
import type {
  LoginForm,
  LoginResponseData,
  UserInfoResponseData
} from '@/api/user/type'
import type { userState } from './type/type'
// 设置||取token
import { SET_TOKEN, GET_TOKEN, DEL_TOKEN } from '@/utils/token'
// 引入路由
import { constantRoute } from '@/router/routes'
// 创建用户小仓库
let useUserStore = defineStore('User', {
  // 存数据
  state: (): userState => {
    return {
      token: GET_TOKEN(),
      menu: constantRoute, //生成菜单所需的
      // 姓名和头像
      username: '',
      avatar: ''
    }
  },
  // 异步||逻辑
  actions: {
    // 登陆
    async userLogin(LoginForm: LoginForm) {
      let res: LoginResponseData = await reqLogin(LoginForm)
      // 登陆成功->status:200
      if (res.code == 200) {
        // pinia存储
        this.token = <string>res.data.token
        // 持久化
        SET_TOKEN(<string>res.data.token)
        return 'ok'
      }
      // 登陆失败201
      else {
        //技巧：如果不抛出Promise异常，该函数返回的都是成功Promise
        return Promise.reject(new Error(res.data.message))
      }
    },
    // 获取用户信息
    async getUserInfo() {
      let res: UserInfoResponseData = await reqUserInfo()
      // console.log(res.data)
      if (res.code == 200) {
        this.username = res.data.checkUser.username
        this.avatar = res.data.checkUser.avatar
      } else {
      }
    },
    // 退出登陆
    async logout() {
      // 清空仓库+清空localstorage的token
      this.username = ''
      this.avatar = ''
      this.token = ''
      DEL_TOKEN()
    }
  },
  getters: {}
})
export default useUserStore
